﻿using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MongoDB.Driver.Builders;

namespace Service
{
    public class MongoHelper<T> where T : class
    {
        private MongoCollection collection;

        public MongoHelper()
        {
            try
            {
                string conn = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
                var client = new MongoClient(conn);
                MongoServer server = client.GetServer();
                MongoDatabase db = server.GetDatabase("cuongdb");
                collection = db.GetCollection<T>(typeof(T).Name.ToLower());
            }
            catch (MongoException me)
            {
                Console.WriteLine(me.Message);
            }
        }

        #region Insert
        public bool Insert(T obj)
        {
            collection.Insert(obj);
            return true;
        }

        public bool Insert(T obj, IndexKeysBuilder index)
        {
            collection.EnsureIndex(index);
            collection.Insert(obj);
            return true;
        }

        public bool Insert(T obj, IndexKeysBuilder index, IndexOptionsBuilder option)
        {
            collection.EnsureIndex(index, option);
            collection.Insert(obj);
            return true;
        }

        #endregion

        #region Delete
        public bool Delete(string id)
        {
            collection.Remove(Query.EQ("_id", id));
            return true;
        }
        #endregion

        #region Update
        public bool Update(string id, UpdateBuilder ub)
        {
            collection.Update(Query.EQ("_id", id), ub);
            return true;
        }
        #endregion

        #region Search
        public T GetByID(string id)
        {
            return (T)collection.FindOneByIdAs(typeof(T), id);
        }

        public T GetOne(IMongoQuery query)
        {
            return (T)collection.FindOneAs(typeof(T), query);
        }

        public IEnumerable<T> GetList(IMongoQuery iquery)
        {
            return collection.FindAs(typeof(T), iquery).Cast<T>();
        }
        #endregion
    }
}
